<script setup lang="ts">
import type { DropdownInstance, TableColumnData, TableInstance } from '@arco-design/web-vue'
import { VueDraggable } from 'vue-draggable-plus'
import type { TableInstanceColumns } from './type'

defineOptions({ name: 'ProTable', inheritAttrs: false })

const props = withDefaults(defineProps<{
  title?: string
  showIndex?: boolean
  disabledTools?: string[] // 禁止显示的工具
  disabledColumnKeys?: string[] // 禁止控制显示隐藏的列
}>(), {
  title: undefined,
  showIndex: false,
  disabledTools: () => [],
  disabledColumnKeys: () => [],
})

const emit = defineEmits<{
  (e: 'refresh'): void
}>()

const attrs = useAttrs()
const slots = useSlots()

const tableRef = ref<TableInstance | null>(null)
const size = ref<TableInstance['size']>('medium')
const isFullscreen = ref(false)

interface SizeItem {
  label: string
  value: TableInstance['size']
}
const sizeList: SizeItem[] = [
  { label: '紧凑', value: 'mini' },
  { label: '偏小', value: 'small' },
  { label: '默认', value: 'medium' },
  { label: '偏大', value: 'large' },
]

const handleSelect: DropdownInstance['onSelect'] = (value) => {
  size.value = value as TableInstance['size']
}

const refresh = () => {
  emit('refresh')
}

const showRefreshBtn = computed(() => !props.disabledTools.includes('refresh'))
const showSizeBtn = computed(() => !props.disabledTools.includes('size'))
const showSettingColumnBtn = computed(
  () => !props.disabledTools.includes('setting') && attrs.columns && (attrs.columns as TableColumnData[]).length,
)
interface SettingColumnItem {
  title: string
  key: string
  show: boolean
  disabled: boolean
}
const settingColumnList = ref<SettingColumnItem[]>([])

// 重置配置列
const resetSettingColumns = () => {
  settingColumnList.value = []
  if (attrs.columns) {
    const arr = attrs.columns as TableInstanceColumns[]
    arr.forEach((item) => {
      settingColumnList.value.push({
        key: item.dataIndex || (typeof item.title === 'string' ? item.title : ''),
        title: typeof item.title === 'string' ? item.title : '',
        show: item.show ?? true,
        disabled: props.disabledColumnKeys.includes(
          item.dataIndex || (typeof item.title === 'string' ? item.title : ''),
        ),
      })
    })
  }
}

watch(
  () => attrs,
  () => {
    resetSettingColumns()
  },
  { immediate: true },
)

// 排序和过滤可显示的列数据
const _columns = computed(() => {
  if (!attrs.columns) {
    return []
  }
  const arr = attrs.columns as TableColumnData[]
  // 显示的dataIndex
  const showDataIndexs = settingColumnList.value
    .filter(i => i.show)
    .map(i => i.key || (typeof i.title === 'string' ? i.title : ''))
  // 显示的columns数据
  const filterColumns = arr.filter(i =>
    showDataIndexs.includes(i.dataIndex || (typeof i.title === 'string' ? i.title : '')),
  )
  const sortedColumns: TableColumnData[] = []
  if (props.showIndex) {
    let render = ({ rowIndex }) => h('span', {}, rowIndex + 1)
    if (props.pagination) {
      render = ({ rowIndex }) => h('span', {}, rowIndex + 1 + (props.pagination.current - 1) * props.pagination.pageSize)
    }
    sortedColumns.push({
      title: '序号',
      width: 66,
      align: 'center',
      render,
    })
  }

  settingColumnList.value.forEach((i) => {
    filterColumns.forEach((j) => {
      if (i.key === (j.dataIndex || j.title)) {
        sortedColumns.push(j)
      }
    })
  })
  return sortedColumns
})

defineExpose({ tableRef })
</script>

<template>
  <div class="pro-table" :class="{ fullscreen: isFullscreen }">
    <a-typography-title :heading="6" style="margin-top: 0">
      <slot name="title-panel">
        {{ title }}
      </slot>
    </a-typography-title>
    <a-row justify="space-between" align="center" class="pro-table-search-panel">
      <slot name="search-panel" />
      <a-divider v-if="slots['search-panel']" />
    </a-row>
    <a-row justify="space-between" align="center" class="pro-table-toolbar">
      <a-space wrap class="toolbar-left" :size="[8, 8]" align="center">
        <slot name="toolbar-left" />
      </a-space>
      <a-space wrap class="toolbar-right" :size="[8, 8]">
        <slot name="toolbar-right" />
        <a-tooltip content="刷新">
          <a-button v-if="showRefreshBtn" class="hover-btn" @click="refresh">
            <template #icon>
              <icon-refresh :size="16" />
            </template>
          </a-button>
        </a-tooltip>
        <a-dropdown v-if="showSizeBtn" @select="handleSelect">
          <a-tooltip content="尺寸">
            <a-button class="hover-btn">
              <template #icon>
                <icon-line-height :size="16" />
              </template>
            </a-button>
          </a-tooltip>
          <template #content>
            <a-doption v-for="item in sizeList" :key="item.value" :value="item.value" :active="item.value === size">
              {{ item.label }}
            </a-doption>
          </template>
        </a-dropdown>
        <a-popover
          v-if="showSettingColumnBtn" trigger="click" position="br"
          :content-style="{ minWidth: '120px', padding: '6px 8px 10px' }"
        >
          <a-tooltip content="列设置">
            <a-button class="hover-btn">
              <template #icon>
                <icon-settings :size="16" />
              </template>
            </a-button>
          </a-tooltip>
          <template #content>
            <div class="table-setting">
              <VueDraggable v-model="settingColumnList">
                <div v-for="item in settingColumnList" :key="item.title" class="drag-item">
                  <div class="drag-item-icon">
                    <icon-drag-dot-vertical />
                  </div>
                  <a-checkbox v-model:model-value="item.show" :disabled="item.disabled">
                    {{ item.title }}
                  </a-checkbox>
                </div>
              </VueDraggable>
            </div>
            <a-divider :margin="6" />
            <a-row justify="center">
              <a-button type="primary" size="mini" long @click="resetSettingColumns">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-row>
          </template>
        </a-popover>
      </a-space>
    </a-row>
    <div class="pro-table-container">
      <a-table
        ref="tableRef"
        row-key="id"
        :stripe="false"
        :size="size"
        :row-class="{ hover: attrs.onRowClick }"
        :scroll="{ x: '100%', y: '100%', minWidth: 960 }"
        column-resizable
        :bordered="false"
        :filter-icon-align-left="true"
        v-bind="{ ...attrs, columns: _columns }"
      >
        <template v-for="key in Object.keys(slots)" :key="key" #[key]="scoped">
          <slot :key="key" :name="key" v-bind="scoped" />
        </template>
      </a-table>
    </div>
  </div>
</template>

<style lang="less" scoped>
.pro-table {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;

  &-toolbar {
    :deep(.arco-form-item-layout-inline) {
      margin-right: 8px;

      &:last-of-type {
        margin-right: 0;
      }
    }

    :deep(.arco-form-layout-inline .arco-form-item) {
      margin-bottom: 0;
    }
  }

  &-container {
    overflow: hidden;
    flex: 1;
    height: 100%;

    :deep(.arco-table-tr.hover) {
      cursor: pointer;
    }
  }
}

.fullscreen {
  padding: @padding;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 1001;
}

.table-setting {
  padding: 1px 0; // 解决 max-height 和 overflow:auto 始终显示垂直滚动条问题
  max-height: 250px;
  overflow: hidden;
  overflow-y: auto;
}

.drag-item {
  display: flex;
  align-items: center;
  cursor: pointer;

  &:hover {
    background-color: var(--color-fill-2);
  }

  &-icon {
    padding-left: 2px;
    padding-right: 2px;
    cursor: move;
  }

  :deep(.arco-checkbox) {
    width: 100%;
    font-size: 12px;

    .arco-checkbox-icon {
      width: 14px;
      height: 14px;
    }
  }
}
</style>
